package com.wang.learn.cloudiot.service;

import com.wang.learn.cloudiot.model.po.Pile;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName TestService
 *
 * @author wang
 * Date 2022/5/5 17:52
 */
@Service
@RequiredArgsConstructor
public class TestService {


    private final PileService pileService;

    public static int num  = 0;

    public ExecutorService executorService  = Executors.newFixedThreadPool(10);

    public CountDownLatch countDownLatch = new CountDownLatch(1);


    public long batchInsert(int num) throws InterruptedException {
        long timeStamp = System.currentTimeMillis();
        long start = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            timeStamp ++;
            Pile pile = new Pile();
            pile.setPower(1.1F);
            pile.setStatus(2.2F);
            pile.setTimestamp(timeStamp);
            SynchronizedDemo runnableDemo = new SynchronizedDemo(countDownLatch, pileService, pile);
            executorService.execute(runnableDemo);
        }
        System.out.println("================================");
        System.out.println("线程集结完毕");
        System.out.println("================================");
        System.out.println("开始批量插入");
        countDownLatch.countDown();
        System.out.println(num);
        long l = System.currentTimeMillis() - start;
        System.out.println("耗时：" + l + "(ms)");
        return l;
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class SynchronizedDemo implements Runnable {

        private CountDownLatch countDownLatch;
        private PileService pileService;
        private Pile pile;


        @Override
        public void run() {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int i = pileService.insertPile(pile);
            System.out.println("插入成功：" + i);
        }

    }


}
